﻿using System;
using System.IO;
using System.Xml.Serialization;

namespace MyBasicLib.Serialization
{
    public class XmlSerializer<T> : ISerializer<T> where T : class
    {
        private static readonly XmlSerializer xs = new XmlSerializer(typeof (T));

        public XmlSerializer()
        {
            if (!typeof (T).IsDefined(typeof (SerializableAttribute), false))
                throw new ArgumentException("T must has SerializableAttribute");
            ;
        }

        #region ISerializer<T> Members

        public byte[] Serializer(T obj)
        {
            Check.Argument.IsNotNull(obj, "obj");
            using (var tw = new MemoryStream())
            {
                xs.Serialize(tw, obj);
                return tw.ToArray();
            }
        }

        public T DeSerializer(byte[] data)
        {
            Check.Argument.IsNotNull(data, "data");
            using (var tw = new MemoryStream(data))
            {
                var obj = xs.Deserialize(tw) as T;
                return obj;
            }
        }

        #endregion
    }
}